﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using XuanXiang.Infrastructure.Attr;
using XuanXiang.Infrastructure.Dto.Request;
using XuanXiang.Infrastructure.Dto.Request.Merchant;
using XuanXiang.Infrastructure.Dto.Response;
using XuanXiang.Infrastructure.Dto.Response.Merchant;
using XuanXiang.Infrastructure.Dto.Response.Promote;
using XuanXiang.Infrastructure.EFCore.MySql;
using XuanXiang.Infrastructure.IOC;
using XuanXiang.Infrastructure.Redis;
using XuanXiang.Infrastructure.Tools;
using XuanXiang.Service.Interface;

namespace XuanXiang.Service.Instance
{
    [Inject_]
    public class Promote_Service : Base_Service, I_Pomote_Service
    {
        private readonly Promote_IOC _promote_IOC;
        private readonly IConfiguration _configuration;
        private readonly RedisListService _redisListService;
        private readonly Merchant_IOC _merchant_IOC;
        private readonly Supplier_IOC _supplier_IOC;
        private readonly Goods_IOC _goods_IOC;

        public Promote_Service(Promote_IOC promote_IOC,
            Supplier_IOC supplier_IOC,
            Merchant_IOC merchant_IOC,
             RedisListService redisListService,
              IConfiguration configuration,
            Goods_IOC goods_IOC)
        {
            _promote_IOC = promote_IOC;
            _configuration = configuration;
            _redisListService = redisListService;
            _merchant_IOC = merchant_IOC;
            _supplier_IOC = supplier_IOC;
            _goods_IOC = goods_IOC;
        }

        /// <summary>
        /// 获取活动商品-商户
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Merchant_PromoteGoods(Fenye_Dto dto)
        {
            //所有活动商品id
            var all = _goods_IOC._goods_EFCore.GetAll(d => d.GisBan == 0 && d.GisShelve == 1 && d.GisPromote==1).Select(d => d.Gid).ToList();
            //所有活动结束的商品id
            var expiredPromotions = await _goods_IOC._goods_EFCore
                .GetAll(d => all.Contains(d.Gid!) &&
                d.GpromoteEnd!.Value < DateTime.Now)
                .Select(d => d.Gid)
                .ToListAsync();
            //修改结束的活动商品的状态
            expiredPromotions.ForEach(d => {
                var g = _goods_IOC._goods_EFCore.GetAll(c => c.Gid == d).SingleOrDefault();
                g.GisPromote = 0;
                g.GpromotePrice = 0;
                g.GpromoteBegin = null;
                g.GpromoteEnd= null;
                _goods_IOC._goods_EFCore.Update(g);
            });
            _goods_IOC._goods_EFCore.SaveChanges();

            //清除购物车中活动结束的商品
            // 2. 处理购物车
            var key = _configuration["Redis:Keys:Get_Car_Data"];
            var car = _redisListService.Get(key + dto.id);



            //清除redis
            var count = expiredPromotions.Count();

            var list = new List<CarDetails_Dto>();
            car.ForEach(d =>
            {
                list.Add(JsonConvert.DeserializeObject<CarDetails_Dto>(d));
            });


            for (int i = 0; i < count; i++)
            {

                string valueToRemove = expiredPromotions[i];//要移除的商品
                var removedata = list.Where(d => d.id == valueToRemove).SingleOrDefault();

                _redisListService.RemoveItemFromList(key + dto.id, JsonConvert.SerializeObject(removedata));
            }

            //所有活动商品
            var data =await _promote_IOC._promote_EFCore
                .GetAll(out int total,dto.page,dto.limit,
                false,o=>o.PendTime,d=>
                all.Contains(d.Pgid!) &&
                d.PbeginTime!.Value<DateTime.Now &&
                d.PendTime!.Value>DateTime.Now)
                .Select(d=>new PromoteGoods_Dto() { 
                id=d.Pgid,
                name=d.Pgname,
                carCount=0,
                promotePrice=d.PpromotePrice,
                s_id=d.Psid
                }).ToListAsync();

            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            data.ForEach(d => {
                d.supplier = supplier.Where(c => c.Sid == d.s_id).Select(c => c.Sname).SingleOrDefault();
            });

            var goods=_goods_IOC._goods_EFCore.GetAll(d=>d.GisShelve==1 && d.GisBan==0).ToList();
            data.ForEach(d => {
                var g = goods.Where(c => c.Gid == d.id && c.GisBan==0 && c.GisShelve==1).SingleOrDefault();
                d.price = g.Gprice;
                d.inventory = g.Ginventory;
                d.specs = g.Gspecs;
                d.photo = g.Gcover;
                d.sales = g.Gsales;
            });




            return Get_Result(0, "ok", new { 
            data=data,
            total=total
            });

            
        }

        /// <summary>
        /// 获取活动列表
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Promotes(Fenye_Dto dto)
        {
            var data =await _promote_IOC._promote_EFCore
                .GetAll(out int total, dto.page, dto.limit, false, 
                o => o.PendTime,d=>d.Pgname.Contains(dto.key))
                .Select(d => new Promotes_Dto(){ 
                id=d.Pid,
                beginTime=d.PbeginTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                endTime=d.PendTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                goodsName=d.Pgname,
                initPrice=d.PinitPrice,
                promotePrice=d.PpromotePrice,
                sales=0,
                promoteSales=0,
                s_id=d.Psid,
                time=d.PcreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                state=d.PendTime.Value<DateTime.Now?1:0
                })
                .ToListAsync();

            var supplier = _supplier_IOC._supplier_EFCore.GetAll().ToList();
            data.ForEach(d => {
                d.supplierName = supplier.Where(c => c.Sid == d.s_id).Select(c => c.Sname).SingleOrDefault();
            });

        
           
            return Get_Result(0, "ok", new { 
            data=data,
            total=total
            });
        }

        /// <summary>
        /// 停止活动
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Stop_Promote(string? id)
        {
          var data=await _promote_IOC._promote_EFCore.GetAll(d=>d.Pid==id).SingleOrDefaultAsync();
            data.PendTime=DateTime.Now.AddSeconds(-5);
            _promote_IOC._promote_EFCore.Update(data);
            var result = await _promote_IOC._promote_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }
    }
}
